﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AxeFrog.Data;
using AxeFrog.Web;

namespace AxeFrog.Web
{
	public abstract class ApiBaseController : BaseController
	{
		[Import]
		private ConnectionContextProvider _ccp;
		private readonly string _defaultConnectionStringName;

		protected ApiBaseController()
		{
		}

		protected ApiBaseController(string defaultConnectionStringName)
		{
			_defaultConnectionStringName = defaultConnectionStringName;
		}

		protected ConnectionContext Connect()
		{
			var cc = _ccp.Connect();
			if(_defaultConnectionStringName != null)
				cc.Specify(_defaultConnectionStringName);
			return cc;
		}

		protected JsonResult Error(params string[] errorCodes)
		{
			return Json(new { ErrorCodes = errorCodes });
		}

		protected JsonResult Empty()
		{
			return Json(new { ErrorCodes = new string[0] });
		}

		protected override void OnException(ExceptionContext filterContext)
		{
			filterContext.Result = Json(new
			{
				ErrorCodes = new [] { filterContext.Exception.GetType().FullName },
				ErrorMessage = filterContext.Exception.Message,
				ErrorDetails = filterContext.Exception.ToString()
			});
			filterContext.ExceptionHandled = true;
			base.OnException(filterContext);
		}
	}
}
